﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SchoolManagerMVC.BusinessAbstract.Interfaces;
using SchoolManagerMVC.Repository.EntityFramework;
using SchoolManagerMVC.Web.Models;
using SchoolManagerMVC.Web.Areas.Faculty.ViewModels;
using System.Web.Security;
using SchoolManagerMVC.BusinessConcrete.Reporting;

namespace SchoolManagerMVC.Web.Areas.Faculty.Controllers
{
    [Authorize(Roles = Constants.OfficeAdmin + "," + Constants.Admin + "," + Constants.FacultyMember)]
    public class HomeController : Controller
    {
        /// <summary>
        /// Faculty Area
        /// </summary>
        private IRepository _repo;
        private IMembership _membership;

        public HomeController(IRepository repo, IMembership membership)
        {
            _repo = repo;
            if (_repo == null)
                throw new NullReferenceException();

            _membership = membership;
            if (_membership == null)
                throw new NullReferenceException();
        }

        public ActionResult Index()
        {
            if (User.IsInRole(Constants.Admin) || User.IsInRole(Constants.OfficeAdmin))
            {
                IEnumerable<FacultyMember> result = _repo.GetAll<FacultyMember>();
                if (result != null)
                    result = result.ToList().OrderBy(e => e.LastName);
                return View("Index", result);
            }

            else if (User.IsInRole(Constants.FacultyMember))
                return View("Details", _membership.getUserID(User.Identity.Name));

            else
                return RedirectToRoute("Default");
        }

        public ActionResult Create()
        {
            if (User.IsInRole(Constants.Admin) || User.IsInRole(Constants.OfficeAdmin))
                return View("Create");
            else
                return RedirectToRoute("Default");
        }

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "UniqueID")] FacultyCreationViewModel facultyVM)
        {
            if (!User.IsInRole(Constants.Admin) && !User.IsInRole(Constants.OfficeAdmin))
                return RedirectToRoute("Default");

            if (ModelState.IsValid)
            {
                var result = _membership.createUser(facultyVM.registerModel.UserName, facultyVM.registerModel.Password, facultyVM.registerModel.Email);
                if (result == MembershipCreateStatus.Success)
                {
                    _repo.Add<FacultyMember>(new FacultyMember()
                    {
                        UniqueID = _membership.getUserID(facultyVM.registerModel.UserName),
                        FirstName = facultyVM.facultyMember.FirstName,
                        LastName = facultyVM.facultyMember.LastName,
                        Age = facultyVM.facultyMember.Age,
                        Salary = facultyVM.facultyMember.Salary
                    });

                    _membership.addUserToRole(facultyVM.registerModel.UserName, Constants.Student);
                    return RedirectToRoute("Faculty_Default");
                }
                else
                {
                    ModelState.AddModelError("", MembershipError.ErrorCodeToString(result));
                }
            }
            return View("Create", facultyVM);
        }

        public ActionResult Details(Guid id)
        {
            FacultyMember result = (FacultyMember)_repo.GetSingle<FacultyMember>(e => e.UniqueID == id);
            return View("Details",result);
        }

        public ActionResult Delete(Guid id)
        {
            if (!User.IsInRole(Constants.Admin) && !User.IsInRole(Constants.OfficeAdmin))
                return RedirectToRoute("Default");

            return View("Delete", _repo.GetSingle<FacultyMember>(e => e.UniqueID == id));
        }

        [HttpPost]
        public ActionResult Delete(FacultyMember facultyMember)
        {
            if (!User.IsInRole(Constants.Admin) && !User.IsInRole(Constants.OfficeAdmin))
                return RedirectToRoute("Default");

            var message = _repo.Remove<FacultyMember>((_repo.GetSingle<FacultyMember>(e => e.UniqueID == facultyMember.UniqueID) as FacultyMember));

            if (message.result)
                return RedirectToAction("Index");

            ViewBag.Message = message.Message;
            return View("Delete", _repo.GetSingle<FacultyMember>(e => e.UniqueID == facultyMember.UniqueID));
        }        

        public ActionResult Edit(Guid id)
        {
            if (!User.IsInRole(Constants.Admin) && !User.IsInRole(Constants.OfficeAdmin))
                return RedirectToRoute("Default");

            var result = _repo.GetSingle<FacultyMember>(e => e.UniqueID == id) as FacultyMember;
            if (result == null)
                return RedirectToAction("Index");

            return View("Edit", result);
        }

        [HttpPost]
        public ActionResult Edit(FacultyMember facultyMember)
        {
            if (!User.IsInRole(Constants.Admin) && !User.IsInRole(Constants.OfficeAdmin))
                return RedirectToRoute("Default");

            if (ModelState.IsValid)
            {
                try
                {
                    var result = _repo.GetSingle<FacultyMember>(e => e.UniqueID == facultyMember.UniqueID) as FacultyMember;
                    mapToFaculty(ref result, facultyMember);
                    _repo.Update<FacultyMember>(result);
                    ViewBag.Message = "Record Saved";
                    return RedirectToAction("Details", new { id = facultyMember.UniqueID });
                }
                catch
                {
                    ViewBag.Message = "There was an error saving";
                }
            }
            return View("Edit", facultyMember);
        }

        private void mapToFaculty(ref FacultyMember result, FacultyMember facultyMember)
        {
            result.FirstName = facultyMember.FirstName;
            result.LastName = facultyMember.LastName;
            result.Age = facultyMember.Age;
            result.Salary = facultyMember.Salary;
        }

        /*
         [HttpPost]
        public ActionResult MultiDelete(Guid[] selectedItems)
        {
            if (selectedItems!=null)
            {
                foreach (var curr in selectedItems)
                {
                    _repo.Remove<FacultyMember>(_repo.GetSingle<FacultyMember>(e => e.UniqueID == curr) as FacultyMember);
                }
            }

            return RedirectToAction("Index");
        }
         */
    }
}
